// @flow
import React from 'react'
import { Menu, Dropdown, Icon } from 'antd'
import { connect } from 'react-redux'
import { withRouter } from 'react-router'
import universalFetch, { LoginFetch, handleFetchError } from 'store/modules/fetch'
import ChangePsw from 'components/ChangePsw'
import PersonalSet from 'components/PersonalSet'
import styles from './ProfileAvatar.css'
import { saveUserId } from 'store/modules/user'

type Props = {
  saveUserId: Function,
  userId: string,
  history: Object
}
type State = {
  userName: string,
  photo: string
}
class ProfileAvatar extends React.Component {
  state: State
  props: Props
  loginOut: Function
  showUser: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      userName: '',
      photo: ''
    }
    this.loginOut = this.loginOut.bind(this)
    this.showUser = this.showUser.bind(this)
  }
  componentWillMount () {
    const { userId } = this.props
    this.showUser(userId)
  }
  componentWillReceiveProps (nextProps) {
    const { userId } = nextProps
    this.showUser(userId)
    // if (userId === '') {
    //   console.log('退出')
    //   this.loginOut()
    // } else {
    //
    // }
  }
  showUser (userId) {
    universalFetch(`${__SERVICE_API__}sys/users/${userId}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        let { name, photo } = json.result
        if (!photo) {
          photo = '/user.jpg'
        }
        this.setState({
          userName: name,
          photo: photo
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  loginOut () {
    const { saveUserId } = this.props
    const token = localStorage.getItem('asset_token')
    let values = {}
    values['loginName'] = this.state.userName
    values['token'] = token
    universalFetch(`${__SERVICE_API__}analysis/redis/logout`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(values)
      })
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        saveUserId(' ')
        localStorage.setItem('asset_token', '')
        window.location.href = '/login'
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
    // history.push(`/login`)
  }
  render () {
    const { userName } = this.state
    return (
      <div className={styles['container']}>
        <img className={styles['avatar']} src={this.state.photo} />
        <Dropdown overlay={
          <Menu>
            <Menu.Item key='1'>
              <PersonalSet />
            </Menu.Item>
            <Menu.Item key='2'>
              <ChangePsw />
            </Menu.Item>
            <Menu.Item key='3'>
              <a onClick={this.loginOut}>退出</a>
            </Menu.Item>
          </Menu>
        }>
          <a className={styles['link']}>
            {userName} <Icon type='down' />
          </a>
        </Dropdown>
      </div>
    )
  }
}
const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default withRouter(connect(mapStatesToProps, { saveUserId })(ProfileAvatar))
